package blue.http.internal.core.handler.parameter;

import blue.base.core.common.ErrorCode;
import blue.http.core.message.HttpRequest;
import blue.http.core.message.WebSocketRequest;
import blue.http.internal.core.parser.RequestParamConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;

/**
 * @author Jin Zheng
 * @since 1.0 2021-01-22
 */
public class BodyJsonParamHandler implements ParamHandler {
	public BodyJsonParamHandler() {
	}

	@Override
	public Object handle(RequestParamConfig config, Object request) {
		String body = this.getBody(request);
		if (body == null || body.isEmpty()) {
			if (config.isParamAnnotationRequired()) {
				throw ErrorCode.REQUIRED.newException(config.getName());
			}

			return null;
		}
		if (config.getParamAnnotationValue().isEmpty()) {
			Object target = ParamHandlerUtil.convert(config, body);
			return target;
		}

		JSONObject object = JSON.parseObject(body);
		Object target = JSONPath.eval(object, config.getParamAnnotationValue());
		if (target == null && config.isParamAnnotationRequired()) {
			throw ErrorCode.REQUIRED.newException(config.getName());
		}
		if (target instanceof JSONObject) {
			Object subTarget = ((JSONObject) target).toJavaObject(config.getParamClazz());
			ParamHandlerUtil.valid(config, subTarget);
			return subTarget;
		}
		return ParamHandlerUtil.convert(config, target);
	}

	private String getBody(Object request) {
		if (request instanceof HttpRequest) {
			return ((HttpRequest) request).getContent();
		} else if (request instanceof WebSocketRequest) {
			return ((WebSocketRequest) request).getContent();
		}
		return null;
	}
}
